import axios from 'axios'
import {Notify, Toast} from 'vant'
import tools from '@/utils/tools.js'

let cancel, promiseArr = {}
const CancelToken = axios.CancelToken


// 基础url,如果是多环境配置这样写，也可以写死。
// axios.defaults.baseURL = import.meta.env.VITE_BASE_URL
//设置默认请求头
axios.defaults.headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
}
//设置超时时间 单位毫秒
axios.defaults.timeout = 20000


// 错误处理函数
const err = (error) => {
    let code = error.code
    console.log(error)
    if (code === "ECONNABORTED") {
        Toast.fail("请求超时！");
    } else if (code === "ERR_NETWORK") {
        Toast.fail("登录超时，请重新登录！");
        tools.removeUser()
    } else if (code === "ERR_BAD_REQUEST") {
        Toast.fail("未找到当前页面");
    } else {
        Toast.fail(error.message);
    }
    return Promise.reject(error)
}

// request interceptor(请求拦截器)
axios.interceptors.request.use(config => {
//   const token = Vue.ls.get(ACCESS_TOKEN)
    const token = localStorage.getItem('token') || $cookies.get("token")
    if (token) {
        config.headers['token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
    }
    return config
}, err)

// response interceptor（接收拦截器）
axios.interceptors.response.use((response) => {
    const res = response.data
    if (res.code !== 200) {
        // 401:未登录;
        if (res.code === 401) {
            tools.removeUser()
            Notify({type: 'danger', message: '当前未登录，请先登录！'});
        } else if (res.code === 403) {
            Toast.fail('没有权限拒绝访问！');
        } else {
            // Toast.fail(res.message || res.msg);
        }
        return response
    } else {
        return response
    }
}, err)

//默认暴露
export default {
    get(url, params) {
        return new Promise((resolve, reject) => {

            axios.defaults.headers['Cache-Control'] = 'no-cache';
            axios.defaults.headers['If-Modified-Since'] = '0';
            axios.defaults.headers['Content-Type'] = 'application/json';
            axios.defaults.headers['If-Modified-Since'] = '0';
            axios.defaults.headers['xxx'] = '022';

            axios({
                method: 'get',
                baseURL: process.env.HTTP_URL,
                url,
                params: params,
                headers: {
                    Authorization: "213123123123"
                },
                cancelToken: new CancelToken(c => {
                    cancel = c;
                })
            }).then(res => {
                resolve(res);
            }).catch(err => {
                reject(err)
            });
        });
    },
    post(url, params) {
        return new Promise((resolve, reject) => {

            axios.defaults.headers['Cache-Control'] = 'no-cache';
            axios.defaults.headers['If-Modified-Since'] = '0';
            axios.defaults.headers['Content-Type'] = 'application/json';

            axios({
                method: 'post',
                baseURL: process.env.HTTP_URL,
                url,
                data: params,
                headers: {
                    // Authorization: author,
                },
                cancelToken: new CancelToken(c => {
                    cancel = c;
                })
            }).then(res => {
                resolve(res);
            }).catch(err => {
                reject(err)
            });
        });
    },
    postForm(url, params) {
        return new Promise((resolve, reject) => {

            axios.defaults.headers['Cache-Control'] = 'no-cache';
            axios.defaults.headers['If-Modified-Since'] = '0';
            axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';

            axios({
                method: 'post',
                baseURL: process.env.HTTP_URL,
                url,
                data: params,
                headers: {
                    // Authorization: author,
                },
                cancelToken: new CancelToken(c => {
                    cancel = c;
                })
            }).then(res => {
                resolve(res);
            }).catch(err => {
                reject(err)
            });
        });
    },
    blobGet(url, params) {
        return new Promise((resolve, reject) => {
            // 异步对象
            let ajax = new XMLHttpRequest();

            // post请求 url 是不需要改变
            ajax.open('get', process.env.HTTP_URL, +url, true);
            ajax.responseType = 'blob';
            // 需要设置请求报文
            ajax.setRequestHeader('Content-Type', 'application/json');
            ajax.setRequestHeader('If-Modified-Since', '0');
            ajax.setRequestHeader('Cache-Control', 'no-cache');
            // 发送请求
            ajax.send();

            // 注册事件
            ajax.onreadystatechange = function () {
                // 在事件中 获取数据 并修改界面显示
                if (ajax.readyState == 4) {

                    if (ajax.status == 200) {
                        resolve({
                            data: ajax.response != undefined ? ajax.response : ajax.responseText,
                            code: 1
                        });
                    } else {
                        resolve({
                            data: ajax.response != undefined ? ajax.response : ajax.responseText,
                            code: 0
                        });
                    }
                }
            }
        });
    },
}
